package com.yklx.youke.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class MessageController {

    // 获取所有消息
    @GetMapping("/messages")
    public ResponseEntity<List<Map<String, Object>>> getMessages(
            @RequestParam(required = false) String messageType,
            @RequestParam(required = false) String senderId,
            @RequestParam(required = false) String receiverId,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 模拟一些消息数据
            Map<String, Object> message1 = Map.ofEntries(
                    Map.entry("messageId", UUID.randomUUID().toString()),
                    Map.entry("title", "系统通知"),
                    Map.entry("content", "这是一条系统通知消息"),
                    Map.entry("type", "SYSTEM"),
                    Map.entry("senderId", "system"),
                    Map.entry("senderName", "系统"),
                    Map.entry("receiverId", "admin"),
                    Map.entry("receiverName", "管理员"),
                    Map.entry("status", "READ"),
                    Map.entry("createdAt", LocalDateTime.now()),
                    Map.entry("readAt", LocalDateTime.now())
            );

            Map<String, Object> message2 = Map.ofEntries(
                    Map.entry("messageId", UUID.randomUUID().toString()),
                    Map.entry("title", "用户注册提醒"),
                    Map.entry("content", "有新用户注册，请及时审核"),
                    Map.entry("type", "NOTICE"),
                    Map.entry("senderId", "system"),
                    Map.entry("senderName", "系统"),
                    Map.entry("receiverId", "admin"),
                    Map.entry("receiverName", "管理员"),
                    Map.entry("status", "UNREAD"),
                    Map.entry("createdAt", LocalDateTime.now().minusHours(1)),
                    Map.entry("readAt", null)
            );

            List<Map<String, Object>> messages = List.of(message1, message2);
            return ResponseEntity.ok(messages);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    // 获取单个消息
    @GetMapping("/messages/{messageId}")
    public ResponseEntity<Map<String, Object>> getMessage(@PathVariable String messageId) {
        try {
            Map<String, Object> message = Map.ofEntries(
                    Map.entry("messageId", messageId),
                    Map.entry("title", "示例消息"),
                    Map.entry("content", "这是一个示例消息内容"),
                    Map.entry("type", "PERSONAL"),
                    Map.entry("senderId", "1"),
                    Map.entry("senderName", "发送者姓名"),
                    Map.entry("receiverId", "2"),
                    Map.entry("receiverName", "接收者姓名"),
                    Map.entry("status", "READ"),
                    Map.entry("createdAt", LocalDateTime.now()),
                    Map.entry("readAt", LocalDateTime.now())
            );
            return ResponseEntity.ok(message);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    // 创建新消息
    @PostMapping("/messages")
    public ResponseEntity<Map<String, Object>> createMessage(@RequestBody Map<String, Object> messageData) {
        try {
            String messageId = UUID.randomUUID().toString();
            
            // 安全地获取字段值，避免类型转换错误
            String title = getStringValue(messageData.get("title"), "");
            String content = getStringValue(messageData.get("content"), "");
            String type = getStringValue(messageData.getOrDefault("type", "PERSONAL"), "PERSONAL");
            String senderId = getStringValue(messageData.get("senderId"), "");
            String receiverId = getStringValue(messageData.get("receiverId"), "");

            Map<String, Object> response = Map.of(
                "messageId", messageId,
                "title", title,
                "content", content,
                "type", type,
                "senderId", senderId,
                "receiverId", receiverId,
                "createdAt", LocalDateTime.now(),
                "success", true,
                "message", "消息发送成功"
            );
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "消息发送失败: " + e.getMessage()
            ));
        }
    }

    // 更新消息状态（如标记已读/未读）
    @PutMapping("/messages/{messageId}/read-status")
    public ResponseEntity<Map<String, Object>> updateReadStatus(
            @PathVariable String messageId,
            @RequestBody Map<String, Object> requestData) {
        try {
            // 安全地获取布尔值，处理可能的类型不匹配问题
            Object isReadObj = requestData.get("isRead");
            boolean isRead = isReadObj != null ? 
                (isReadObj instanceof Boolean ? (Boolean) isReadObj : 
                 Boolean.parseBoolean(isReadObj.toString())) : false;
                 
            String status = isRead ? "READ" : "UNREAD";
            LocalDateTime readAt = isRead ? LocalDateTime.now() : null;

            Map<String, Object> response = Map.of(
                "messageId", messageId,
                "status", status,
                "readAt", readAt,
                "success", true,
                "message", "状态更新成功"
            );
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "状态更新失败: " + e.getMessage()
            ));
        }
    }

    // 删除消息
    @DeleteMapping("/messages/{messageId}")
    public ResponseEntity<Map<String, Object>> deleteMessage(@PathVariable String messageId) {
        try {
            Map<String, Object> response = Map.of(
                "success", true,
                "message", "消息删除成功"
            );
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "消息删除失败: " + e.getMessage()
            ));
        }
    }
    
    // 辅助方法：安全地获取字符串值
    private String getStringValue(Object obj, String defaultValue) {
        if (obj == null) {
            return defaultValue;
        }
        return obj.toString();
    }
}